package net.borderwars.userserver;

import net.borderwars.util.OurBase64;

import java.io.IOException;
import java.io.Serializable;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Random;

/**
 * @author ehubbard
 *         Date: Mar 10, 2006
 *         Time: 1:46:18 PM
 */
public class Invocation implements Serializable {
    private static Random r = new Random(100);

    public long getId() {
        return id;
    }

    private long id = r.nextLong();
    private String methodName;
    private Class[] types;
    private Object[] args;
    private Integer oid;
    private static final long serialVersionUID = -3031440501596599721L;

    static public Invocation getInvocation(String urlSafe) throws IOException {
        try {
            String base64 = URLDecoder.decode(urlSafe, "UTF-8");
            Object o = OurBase64.decodeObject(base64);
            return (Invocation) o;
        }

        catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return (null);
    }

    public Invocation(final String methodName, final Class[] types, final Object[] args, final Integer oid) {
        this.methodName = methodName;
        this.types = types;
        this.args = args;
        this.oid = oid;
    }

    public String getMethodName() {
        return methodName;
    }

    public Class[] getTypes() {
        return types;
    }

    public Object[] getArgs() {
        return args;
    }

    public Integer getOid() {
        return oid;
    }

    public String toURLSafeString() throws IOException {
        String base64 = OurBase64.encodeObject(this);
        String urlSafe = URLEncoder.encode(base64, "UTF-8");
        return (urlSafe);
    }

    public String toString() {
        StringBuffer rtn = new StringBuffer();
        rtn.append(methodName + "(");
        if (args != null) {
            for (Object o : args) {
                rtn.append(o.toString() + ",");

            }
        } else {
            rtn.append("void");
        }
        rtn.append(")");

        return (rtn.toString());
    }

}
